﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace NinjaToolbox.PhysicsSystem
{
    [DefaultExecutionOrder(-200)]
    public class BVHTreeContainer : MonoBehaviour
    {
        static List<BVHTreeContainer> mContainerList;
        public static List<BVHTreeContainer> ContainerList { get { return mContainerList; } }

        BVHTree mBVHTree;
        public BVHTree Tree { get { return mBVHTree; } }

        public int id;
        public PhysicsBase[] members;
        public int leafCount = 2;


        static BVHTreeContainer()
        {
            mContainerList = new List<BVHTreeContainer>(10);
        }

        public static BVHTreeContainer GetContainerWithID(int id)
        {
            for (int i = 0, iMax = mContainerList.Count; i < iMax; i++)
            {
                var item = mContainerList[i];
                if (item.id == id)
                    return item;
            }

            return null;
        }

        void OnEnable()
        {
            mBVHTree = new BVHTree();
            for (int i = 0, iMax = members.Length; i < iMax; i++)
            {
                mBVHTree.RegistToTree(members[i]);
            }

            mBVHTree.BuildTree(leafCount);

            mContainerList.Add(this);
        }

        void OnDisable()
        {
            for (int i = 0, iMax = members.Length; i < iMax; i++)
            {
                mBVHTree.UnregistFromTree(members[i]);
            }

            mContainerList.Remove(this);
        }
    }
}
